package com.example.mylogin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mylogin.entity.SpatialArea;
import com.example.mylogin.mapper.SpatialAreaMapper;
import com.example.mylogin.pojo.dto.AreaCreateDTO;
import com.example.mylogin.pojo.dto.AreaQueryDTO;
import com.example.mylogin.service.SpatialAreaService;
import lombok.extern.slf4j.Slf4j;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.io.WKBReader;
import org.locationtech.jts.io.WKBWriter;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class SpatialAreaServiceImpl extends ServiceImpl<SpatialAreaMapper, SpatialArea> implements SpatialAreaService {

    private final WKBWriter wkbWriter = new WKBWriter();

    @Override
    public SpatialArea createArea(AreaCreateDTO dto) {
        SpatialArea area = new SpatialArea();
        area.setName(dto.getName());
        area.setBoundary(dto.getBoundary());
        this.save(area);
        return area;
    }

    @Override
    public List<SpatialArea> findAreasContainingPoint(AreaQueryDTO query) {
        List<SpatialArea> areasContainingPoint = new ArrayList<>();
        try {
            byte[] pointBytes = wkbWriter.write(query.getPoint());
            WKBReader reader = new WKBReader();
            Geometry geometry = reader.read(pointBytes); // 将 byte[] 转为 Geometry
            areasContainingPoint = baseMapper.findAreasContaining(geometry);
        } catch (Exception e) {
            log.error("reader.read()失败，参数是{}", query.getPoint());
        }
        return areasContainingPoint;
    }

    @Override
    public List<SpatialArea> findAreasWithinDistance(AreaQueryDTO query) {
        List<SpatialArea> areasWithinDistance = new ArrayList<>();
        try {
            byte[] pointBytes = wkbWriter.write(query.getPoint());
            WKBReader reader = new WKBReader();
            Geometry geometry = reader.read(pointBytes);
            areasWithinDistance = baseMapper.findAreasWithinDistance(geometry, query.getDistance());
        } catch (Exception e) {
            log.error("reader.read()失败，参数是{}, {}", query.getPoint(), query.getDistance());
        }

        return areasWithinDistance;
    }

    @Override
    public Double calculateArea(Long id) {
        return baseMapper.calculateArea(id);
    }
}
